<?php
require_once('Model/DB.php');
require_once('Plugin/Site.php');
require_once('Plugin/Staff.php');

class Model_SiteManage
{
    public function __construct()
    {
        session_name( 'SESS_SITEMANAGE' );
        session_start();
    }
    
    public function checkLogin($check_only = false)
    {
        if ($check_only){
            if (isset($_SERVER['ADMIN_LOGIN']['STAFF_ID'])){
                return true;
            }
            else{
                return false;
            }
        }
        else{
            if(!preg_match("/login.php/",$_SERVER['SCRIPT_NAME'])){
                if( !isset($_SESSION['ADMIN_LOGIN']['STAFF_ID']) ){
        header("Location: ./login.php");
                    exit;
                }
            }
            else{
                return $_SESSION['ADMIN_LOGIN']['STAFF_ID'];
            }
        }        
    }
    public function login($email, $login_pass, $redirect = '')
    {
    	

        $db  = new Model_DB();
        
        $sql = sprintf("SELECT * FROM M_STAFF WHERE email = '%s' AND login_pass = '%s' AND enabled = 1 AND actived = 1", $db->escape($email), $db->escape($login_pass));
  
       
        $db->query( $sql );
        if ($db->res){
            $res  = $db->fetch();
            $site = new Model_Site();
            
            $_SESSION['ADMIN_LOGIN']['STAFF_ID']    = $res['id'];
            $_SESSION['ADMIN_LOGIN']['STAFF_SEQ']   = $res['id'];
            $_SESSION['ADMIN_LOGIN']['STAFF_MAIL']  = $res['email'];
            $_SESSION['ADMIN_LOGIN']['STAFF_NAME']  = $res['staff_name'];
            
            if ($res['image_file'] != ''){
                $staff = new Model_Staff();
                $_SESSION['ADMIN_LOGIN']['STAFF_IMAGE'] = $staff->getStaffImageUrl() . $res['image_file'];
            }
            $_SESSION['ADMIN_LOGIN']['SITE']        = array();
            $_SESSION['DASH_BOARD']['SITE_ID']      = '';

            
            // 管理者は全権限
            if($res['admin_flg'] == 1){
                $_SESSION['ADMIN_LOGIN']['AUTH_CD'] = array_keys($arr_auth);	// ← 旧仕様（複数サイト未対応）
                $sql = "SELECT * FROM SITE_CONFIG WHERE enabled = 1 ORDER BY id ASC";
                $db->query($sql);
                if($db->num_rows()){
                    while($res = $db->fetch()){
                        $site_id = $res['id'];
                        $_SESSION['ADMIN_LOGIN']['SITE'][$site_id] = array();
                        $_SESSION['ADMIN_LOGIN']['SITE'][$site_id][] = 990;
                        $_SESSION['ADMIN_LOGIN']['SITE'][$site_id][] = 1000;
                        if($_SESSION['DASH_BOARD']['SITE_ID'] == ''){
                            $_SESSION['DASH_BOARD']['SITE_ID']   = $site_id;
                            $_SESSION['DASH_BOARD']['SITE_DIR']  = $site->getSiteDir($site_id);
                            $_SESSION['DASH_BOARD']['SITE_NAME'] = $res['site_name'];
                            $_SESSION['DASH_BOARD']['LOGO_FILE'] = $res['logo_file'];
                        }
                    }
                }
                foreach(array_keys($_SESSION['ADMIN_LOGIN']['SITE']) as $site_id){
                    $db->query(sprintf("SELECT * FROM D_SITE_PLUGIN WHERE site_id = '%u'", $site_id));
                    while($res = $db->fetch()){
                        $_SESSION['ADMIN_LOGIN']['SITE'][$site_id][] = $res['auth_cd'];
                    }
                }
            }
            else{
     return false;
                $sql = sprintf("SELECT distinct A.* FROM D_STAFF_AUTH A, SITE_CONFIG S WHERE A.staff_id = '%u' AND A.site_id = S.id AND S.enabled = 1 ORDER BY site_id ASC", $res['id']);
                $db->query($sql);
                while($res = $db->fetch()){
                    $site_id = $res['site_id'];
                    $_SESSION['ADMIN_LOGIN']['SITE'][$site_id] = array();
                    if($_SESSION['DASH_BOARD']['SITE_ID'] == ''){
                        $_SESSION['DASH_BOARD']['SITE_ID']   = $site_id;
                        $_SESSION['DASH_BOARD']['SITE_ID']   = $site_id;
                        $_SESSION['DASH_BOARD']['SITE_DIR']  = $site->getSiteDir($site_id);
                        $_SESSION['DASH_BOARD']['SITE_URL']  = $res['url'];
                        $_SESSION['DASH_BOARD']['SITE_NAME'] = $res['site_name'];
                        $_SESSION['DASH_BOARD']['LOGO_FILE'] = $res['logo_file'];
                    }
                }
        
                $sql = sprintf("select S.site_id, S.role_id from D_STAFF_AUTH S, M_ROLE R, SITE_CONFIG C where S.staff_id = '%u' and S.site_id = R.site_id and S.role_id = R.id and S.role_id is not null and R.enabled = 1 and R.actived = 1 and C.enabled = 1 and S.site_id = C.id order by site_id asc", $res['id']);
                $db->query($sql);
                $roles = array();
                if($db->num_rows()){
                    while($res = $db->fetch()){
                        $roles[] = $res;
                    }
                }
                foreach($roles as $r){
                    $sql = sprintf("select R.auth_cd from D_ROLE_AUTH R, D_SITE_PLUGIN P where R.role_id = '%u' and P.site_id = '%u' and R.auth_cd = P.auth_cd order by auth_cd asc", $r['role_id'], $r['site_id']);
                    $db->query($sql);
                    if($db->num_rows()){
                        while($res = $db->fetch()){
                            $_SESSION['ADMIN_LOGIN']['SITE'][$r['site_id']][] = $res['auth_cd'];
                        }
                    }
                }
        
                $sql = sprintf("select A.* from D_STAFF_AUTH A, SITE_CONFIG S, D_SITE_PLUGIN P where A.staff_id = '%u' and A.site_id = S.id and S.enabled = 1 and A.site_id = P.site_id and A.auth_cd = P.auth_cd ORDER BY site_id ASC, auth_cd ASC", $res['id']);
                $db->query( $sql );
                if( $db->num_rows() ){
                    while( $res = $db->fetch() ){
                        $site_id = $res['site_id'];
                        $auth_cd = $res['auth_cd'];
                        $_SESSION['ADMIN_LOGIN']['SITE'][$site_id][] = $auth_cd;
                    }
                }
            }
            //			$sql = sprintf("SELECT * FROM D_STAFFAUTH WHERE id = %u", mysql_real_escape_string( $_SESSION['ADMIN_LOGIN']['STAFF_SEQ'] ) );
            //			$db->query( $sql );
            //			while( $res = $db->fetch() ){
            //				$_SESSION['ADMIN_LOGIN']['AUTH_CD'][] = $res['auth_cd'];
            //			}
        
            // テンポラリ削除
            //temp_clear( '../../system/temporary/' );


            header('Location: '. ($redirect != '' ? $redirect : './index.php'));
            exit;
        }

        return false;
    }
    public function logout()
    {
        $_SESSION = array();
        session_destroy();
    }
    //
    public function getCurrentSite()
    {
        return $_SESSION['DASH_BOARD']['SITE_ID'];
    }
    public function getCurrentSiteID()
    {
        return getCurrentSite();
    }
    public function getCurrentSiteUrl()
    {
        if ($_SESSION['DASH_BOARD']['SITE_URL'] == ''){
            return 'http://'. $_SERVER['HTTP_HOST'] . '/'. $this->getCurrentSiteDir();
        }
        else{
           return $_SESSION['DASH_BOARD']['SITE_URL'];
        }
    }
    public function getCurrentSiteDir()
    {
        return $_SESSION['DASH_BOARD']['SITE_DIR'];
    }
    public function createDir($dir)
    {
        chdir(SiteManageRootDir . '/htdocs/');
        $dir = str_replace(SiteManageRootDir. '/htdocs/', '', $dir);
        $dir = preg_replace('/^\//', '', $dir);
        $dir = preg_replace('/\/$/', '', $dir);
        foreach(explode('/', $dir) as $target){
            if (!file_exists($target)){
                mkdir($target);
                chmod($target, 0777);
            }
            chdir($target);
        }
    }
    public function isValidPlugin($plugin)
    {
        $site_id = $this->getCurrentSite();
        $config  = __get_config('plugin.ini');
        if (isset($config[$plugin]) && in_array($config[$plugin]['id'], $_SESSION['ADMIN_LOGIN']['SITE'][$site_id]))
        {
            return true;
        }
        return false;
    }
    //
    public function getStaffSiteList()
    {
        return get_staff_site_list();
    }
    public function get_staff_site_list()
    {
        $staff_id = $this->checkLogin();
        $db       = new Model_DB();
        $sql      = sprintf("select * from SITE_CONFIG where enabled = 1 and id in (select distinct site_id from D_STAFF_AUTH where staff_id = %d) order by id asc", $staff_id);
        $list     = array();
        $db->query($sql);
        while($res = $db->fetch()){
            $list[] = $res;
        }
        return $list;
    }
    public function changeSite($site_id)
    {
        return change_site($site_id);
    }
    public function change_site($site_id)
    {
        if(isset($_SESSION['ADMIN_LOGIN']['SITE'][$site_id])){
            $site = new Model_Site();
            $res  = $site->get($site_id);
            $_SESSION['DASH_BOARD']['SITE_ID']   = $site_id;
            $_SESSION['DASH_BOARD']['SITE_DIR']  = $site->getSiteDir($site_id);
            $_SESSION['DASH_BOARD']['SITE_URL']  = $res['url'];
            $_SESSION['DASH_BOARD']['SITE_NAME'] = $res['site_name'];
            $_SESSION['DASH_BOARD']['LOGO_FILE'] = $res['logo_file'];
            return 'OK';
        }
        return '';
    }
    //
    // for Smarty Plugin
    //
    public function _getCategoryList()
    {
        require_once('Plugin/Category.php');
        $category = new Model_Category();
        $list     = array();
        foreach($category->getList(array(), $orderby = 'level, order_num') as $row){
            $list[$row['id']] = $row;
        }
        return $list;
    }
}
?>
